<template>
  <div>
    <div class="dizhi_bianji_1">
      <div :class="this.type_1 == 0 ? 'bianji_tou_1 ' : 'baocun_tou_1'">
        {{ this.type_1 == 1 ? "添加" : "编辑" }}收货地址
      </div>

      <el-form
        status-icon
        class="form_dizhi_1"
        label-width="100px"
        :model="formLabelAlign"
        :rules="rules"
        ref="formLabelAlign"
      >
        <el-form-item label="地区信息">
          <VDistpicker
            @province="onChangeProvince"
            @city="onChangeCity"
            @area="onChangeArea"
            :province="formLabelAlign.Province"
            :city="formLabelAlign.City"
            :area="formLabelAlign.County"
          >
          </VDistpicker>
        </el-form-item>
        <el-form-item label="详细地址" prop="Desc" size="mini">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
            v-model="formLabelAlign.Desc"
          >
          </el-input>
        </el-form-item>

        <el-form-item label="收货人姓名" prop="name" size="mini">
          <el-input v-model="formLabelAlign.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phoneNumber" size="mini">
          <el-input v-model.number="formLabelAlign.phoneNumber"></el-input>
        </el-form-item>
      </el-form>
      <el-switch
        class="baocun_1"
        v-model="value1"
        active-text="设置为默认收货地址"
      >
      </el-switch>
    </div>
    <el-button type="primary" size="mini" @click="submitForm('formLabelAlign')"
      >保存</el-button
    >
    <el-button
      type="primary"
      size="mini"
      @click="xiugai_quxiao"
      v-if="this.type_1 == 0"
      >取消修改</el-button
    >
  </div>
</template>

<script>
import axios from "axios";
import VDistpicker from "v-distpicker";
export default {
  components: { VDistpicker },
  props: ["dizhi", "tableData", "type_1", "dialogVisible"],

  data() {
    var checkName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("不能为空"));
      } else {
        callback();
      }
    };
    var checkName1 = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("不能为空"));
      } else {
        callback();
      }
    };

    var checkNumber = (rule, value, callback) => {
      var regMobile = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (!value) {
        return callback(new Error("手机号不能为空"));
      }

      if (!Number.isInteger(value)) {
        callback(new Error("请输入数字值"));
      } else {
        if (!regMobile.test(value)) {
          callback(new Error("请输入有效的11位手机号码！"));
        } else {
          callback();
        }
      }
    };

    return {
      // type_1: 1, //判断是修改状态还是添加状态  默认添加状态
      formLabelAlign: {
        name: "",
        phoneNumber: "",
        yzbm: "",
        Province: "",
        County: "",
        City: "",
        Desc: "",
        addressId: "",
        index: "",
      },
      userInfo: "",
      
      value1: false,
      rules: {
        phoneNumber: [{ validator: checkNumber, trigger: "blur" }],
        name: [{ validator: checkName, trigger: "blur" }],
        Desc: [{ validator: checkName1, trigger: "blur" }],
      },
    };
  },
  methods: {
    onChangeProvince(a) {
      this.formLabelAlign.Province = a.value;
      ;
    },
    onChangeCity(a) {
      this.formLabelAlign.City = a.value;
    },
    onChangeArea(a) {
      this.formLabelAlign.County = a.value;
    },
    submitForm(formLabelAlign) {
      //添加、修改收货地址
      this.$refs[formLabelAlign].validate(async (valid) => {
        if (valid) {
          const address = {};
          //   this.loading = true; //开始加载动画
          if (this.type_1 == 1) {
            if (this.value1 == 1) {
              for (let item of this.tableData) {
                item.addressDefault = 0;
              }

              for (let item of this.tableData) {
                await axios
                  .put(
                    "/fl-address/modifyAddressByAddressId",
                    {
                      addressDefault: 0,
                      name: item.receiveName,
                      phoneNum: item.receivePhoneNumber,
                      receiveCity: item.receiveCity,
                      receiveCounty: item.receiveCounty,
                      receiveDesc: item.receiveDesc,
                      receiveProvince: item.receiveProvince,
                      userId: item.userId,
                      addressId: item.addressId,
                    },
                    {
                      headers: {
                        Authorization: localStorage.getItem("token"),
                      },
                    }
                  )
                  .then((res) => {
                    ;
                  });
              }
            }

            axios
              .post(
                "/fl-address/addAddress",
                {
                  addressDefault: this.value1,
                  name: this.formLabelAlign.name,
                  phoneNum: this.formLabelAlign.phoneNumber,
                  receiveCity: this.formLabelAlign.City,
                  receiveCounty: this.formLabelAlign.County,
                  receiveDesc: this.formLabelAlign.Desc,
                  receiveProvince: this.formLabelAlign.Province,
                  userId: this.userInfo.userId,
                },
                {
                  headers: {
                    Authorization: localStorage.getItem("token"),
                  },
                }
              )
              .then((res) => {
                ;
                axios
                  .get(
                    "/fl-address/getAddressByAddressId",
                    {
                      params: {
                        addressId: res.data.data,
                      },
                      headers: {
                        Authorization: localStorage.getItem("token"),
                      },
                    }
                  )
                  .then((res) => {
                      for (let item of this.tableData) {
                      item.type = 0;
                    } 
                  this.tableData.push(res.data.data);
                     this.$set(res.data.data, "type", 1); //添加地址是否被选中属性
                     
                  
                   
                    if (res.data.code == 200) {
                      this.dialogVisible = false;
                      this.$message({
                        message: "添加地址成功",
                        type: "success",
                      });
                      this.$emit("guanbi");
                      this.$emit("xz_dizi");
                    } else {
                      this.$message.error("添加失败请重试");
                    }
                  });
              });
          } else {
            //修改收货地址
            if (this.value1 == 1) {
              //判断是否修改了默认地址
              for (let item of this.tableData) {
                item.addressDefault = 0;
              }

              for (let item of this.tableData) {
                await axios
                  .put(
                    "/fl-address/modifyAddressByAddressId",
                    {
                      addressDefault: 0,
                      name: item.receiveName,
                      phoneNum: item.receivePhoneNumber,
                      receiveCity: item.receiveCity,
                      receiveCounty: item.receiveCounty,
                      receiveDesc: item.receiveDesc,
                      receiveProvince: item.receiveProvince,
                      userId: item.userId,
                      addressId: item.addressId,
                    },
                    {
                      headers: {
                        Authorization: localStorage.getItem("token"),
                      },
                    }
                  )
                  .then((res) => {
                    ;
                  });
              }
             
              
              // this.$refs.table.sort("addressDefault", "descending");
            }

            axios
              .put(
                "/fl-address/modifyAddressByAddressId",
                {
                  addressDefault: this.value1,
                  name: this.formLabelAlign.name,
                  phoneNum: this.formLabelAlign.phoneNumber,
                  receiveCity: this.formLabelAlign.City,
                  receiveCounty: this.formLabelAlign.County,
                  receiveDesc: this.formLabelAlign.Desc,
                  receiveProvince: this.formLabelAlign.Province,
                  userId: this.userInfo.userId,
                  addressId: this.formLabelAlign.addressId,
                },
                {
                  headers: {
                    Authorization: localStorage.getItem("token"),
                  },
                }
              )
              .then((res) => {
                ;
                
                axios
                  .get(
                    "/fl-address/getAddressByAddressId",
                    {
                      params: {
                        addressId: this.formLabelAlign.addressId,
                      },
                      headers: {
                        Authorization: localStorage.getItem("token"),
                      },
                    }
                  )
                  .then((res) => {
                    ;
                    this.$set(res.data.data, "type", 1); //添加已选中的状态

                    this.formLabelAlign.addressId;
                    let index = 0;
                    for (let i of this.tableData) {
                      index++;

                      if (i.type == 1) {
                        ; //获取索引 替换数组
                        this.tableData.splice(index - 1, 1, res.data.data);
                        
                      }
                    }

                    // this.tableData.push(res.data.data);

                    ;
                    if (res.data.code == 200) {
                      this.dialogVisible = false;
                      this.$message({
                        message: "修改地址成功",
                        type: "success",
                      });
                       this.$emit("guanbi");
                      this.$emit("xz_dizi");
                    } else {
                      this.$message.error("修改失败请重试");
                    }
                    // this.tableData.push(res.data.data)
                    ;
                  });
              });
          }

          // this.loading = false;
        } else if (this.formLabelAlign.County == "区") {
          this.dialogVisible = true;
          this.$message.error("地区信息请选择完整");
        } 
        // else {
        //   this.dialogVisible = true;
        //   ;
        //   this.$message.error("地址格式错误，请检查");
        //   return false;
        // }
      });
    },
    xiugai_quxiao() {
      //取消修改
      this.type = 1;
      this.formLabelAlign.name = "";
      this.formLabelAlign.phoneNumber = "";
      this.formLabelAlign.yzbm = 435400;
      this.formLabelAlign.Province = "";
      this.formLabelAlign.City = "";
      this.formLabelAlign.County = "";
      this.formLabelAlign.Desc = "";

      this.value1 = "false";
      this.$message({
        message: "已取消修改",
        type: "success",
      });
    },
    handleEdit(val) {
      //渲染要修改的地址数据
      this.formLabelAlign.name = val.receiveName;
      this.formLabelAlign.phoneNumber = Number(val.receivePhoneNumber);
      this.formLabelAlign.yzbm = 435400;
      this.formLabelAlign.Province = val.receiveProvince;
      this.formLabelAlign.City = val.receiveCity;
      this.formLabelAlign.County = val.receiveCounty;
      this.formLabelAlign.Desc = val.receiveDesc;
      this.formLabelAlign.addressId = val.addressId;
      this.type_1 = 0;

      if (val.addressDefault == 1) this.value1 = true;
      else this.value1 = false;
    },
  
  },
  created() {
    // this.getdizhilist();
    if (this.type_1 == 0) this.handleEdit(this.dizhi);
    this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
    ;

  },
  watch: {
    dizhi() {
      //监听组件传值变化
      this.handleEdit(this.dizhi);
    },
  },
};
</script>

<style lang="less">
.dizhi_bianji_1 {
  position: relative;

  .bianji_tou_1 {
    width: 100%;
    height: 30px;
    line-height: 30px;
    background: #409eff;
    margin-bottom: 20px;
  }
  .baocun_tou_1 {
    width: 100%;
    height: 30px;
    line-height: 30px;
    background: #f3f8fe;
    margin-bottom: 20px;
  }
  .baocun_1 {
    margin-bottom: 20px;
  }
  .form_dizhi_1 {
    width: 100%;
    margin-bottom: 5px;
  }
  .dizhi_xz_1 {
    height: 10px;
   
  }
}
</style>
